import { PropType, defineComponent, provide, computed, ComputedRef } from 'vue';
import { showSlot } from '~/src/utils/hooks';

// 定义选项数据类型
export interface OptionData {
    value: string | number;
    label: string | number | undefined;
}

export interface IProvideExpose {
    /** 当前的结果 */
    value: ComputedRef<string | number | undefined>,
    /** 响应回调 */
    callBack: (c: OptionData) => void
}

export default defineComponent({
    // 明确事件类型定义
    emits: {
        "change": (val: OptionData) => true,
        "update:modelValue": (val: string | number) => true
    },
    props: {
        /** v-model */
        modelValue: {
            type: [String, Number] as PropType<string | number>,
            required: false,
            default: ''
        },
    },
    setup(props, { slots, emit, attrs }) {
        // 计算属性 - 当前选中值
        const modelValueComputed = computed(() => {
            return props.modelValue;
        });

        // 提供给子组件的方法
        provide("buttonSelect", {
            value: modelValueComputed,
            callBack(val: OptionData) {
                // 更新v-model绑定值
                emit("update:modelValue", val.value);
                // 触发change事件，传递完整数据
                emit("change", val);
            }
        } as IProvideExpose);

        return () => (
            <div style={{ display: "flex" }} {...attrs}>
                {showSlot(slots)}
            </div>
        );
    }
})
